//
//  OutputPassageViewController.m
//  NotMadLibs
//
//  Created by crpatte2 on 11/2/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "OutputPassageViewController.h"



@implementation OutputPassageViewController
@synthesize textView, inputPath, inputtedWords, background;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:inputPath ofType:@"txt"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDirectory = [documentPaths objectAtIndex:0];
        path = [NSString stringWithFormat:@"%@/%@.txt", docDirectory, inputPath];
    }
    
    NSString *text = [NSString stringWithContentsOfFile:path
                                               encoding:NSUTF8StringEncoding
                                                  error:NULL];
    
    NSString *displayText = [self parse:text];
    self.textView.text = displayText;
   
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(NSString *)loadText:(NSString *) path {
    NSString *textString = [NSString stringWithContentsOfFile:path 
                                                     encoding:NSUTF8StringEncoding
                                                        error:NULL];
    
    return textString;
}

-(NSString *)parse:(NSString *)input{
    //I fixed the problem with the \n getting removed by doing 'whitespaceCharacterSet' instead of 'whitespaceAndNewLineCharacterSet'
    NSArray *words = [input componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSArray *parsedWords = [NSArray array];
    
    int wordCount = [words count];
    for (int i = 0; i < wordCount; i++){
        NSString *word = [words objectAtIndex:i];
        NSString *parsedWord = @"";
        for (int j = 0; j < [word length]; j++){
            NSString *achar = [NSString stringWithFormat:@"%c", [word characterAtIndex:j]];
            if ([achar isEqualToString:@"<"]){
                NSString *tagNum = @"";
                while (![achar isEqualToString:@"_"]) {
                    j++;
                    achar = [NSString stringWithFormat:@"%c", [word characterAtIndex:j]];
                }
                j++;
                achar = [NSString stringWithFormat:@"%c", [word characterAtIndex:j]];
                while (![achar isEqualToString:@">"]) {
                    tagNum = [tagNum stringByAppendingString:achar];
                    j++;
                    achar = [NSString stringWithFormat:@"%c", [word characterAtIndex:j]];
                }
                int number = [tagNum intValue];
                parsedWord = [parsedWord stringByAppendingString:[inputtedWords objectAtIndex:number]];
            }
            else{
                parsedWord = [parsedWord stringByAppendingString:achar];
            }
        }
        parsedWords = [parsedWords arrayByAddingObject:parsedWord];
    }
    
    return [parsedWords componentsJoinedByString:@" "];
 
}

-(NSString *)parseForEmail:(NSString *)input{
    NSArray *words = [input componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSArray *parsedWords = [NSArray array];
    
    int wordCount = [words count];
    for (int i = 0; i < wordCount; i++){
        NSString *word = [words objectAtIndex:i];
        NSString *parsedWord = @"";
        for (int j = 0; j < [word length]; j++){
            NSString *achar = [NSString stringWithFormat:@"%c", [word characterAtIndex:j]];
            if ([achar isEqualToString:@"\n"]){
                parsedWord = [parsedWord stringByAppendingString:@"<br>"];
            }
            else{
                parsedWord = [parsedWord stringByAppendingString:achar];
            }
        }
        parsedWords = [parsedWords arrayByAddingObject:parsedWord];
    }
    
    return [parsedWords componentsJoinedByString:@" "];
}

-(IBAction)sendInAppSMS:(id)sender {
    MFMessageComposeViewController *messageVC = [[[MFMessageComposeViewController alloc] init] autorelease];
    
    if([MFMessageComposeViewController canSendText]) {
        NSString *body = [NSString stringWithFormat:@"The following passage was created once I inserted some words into it! <br>%@<br>How hilarious is that?!?!?!", [self parseForEmail:self.textView.text]];
        messageVC.body = body;
        messageVC.messageComposeDelegate = self;
        [self presentModalViewController:messageVC animated:YES];
    }
    
}

-(IBAction)sendEmail:(id)sender{
    if ([MFMailComposeViewController canSendMail]){
        MFMailComposeViewController *composeVC = [[[MFMailComposeViewController alloc] init] autorelease];
        composeVC.mailComposeDelegate = self;
        NSString *display = [self parseForEmail:self.textView.text];
        
        [composeVC setSubject:@"Read this hilarious translation!"];
        NSString *body = [NSString stringWithFormat:@"The following passage was created once I inserted some words into it! <br><br>%@<br>How hilarious is that?!?!?!", display];
        
        [composeVC setMessageBody:body isHTML:YES];
        
        if (composeVC != nil){
            [self presentModalViewController:composeVC animated:YES];
        }
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Email" message: @"No email capabilities exist on this device! Sorry!"
                                                       delegate:self cancelButtonTitle:@"Oh no! I guess I'll just have to buy a new iPhone..." otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
    UIAlertView *alert;
	switch (result) {
		case MessageComposeResultCancelled:
			break;
		case MessageComposeResultFailed:
            alert = [[UIAlertView alloc] initWithTitle:@"MyApp" 
                                               message:@"Unknown Error"
                                              delegate:self 
                                     cancelButtonTitle:@"OK" 
                                     otherButtonTitles: nil];
			[alert show];
			[alert release];
			break;
		case MessageComposeResultSent:
            
			break;
		default:
			break;
	}
	[self dismissModalViewControllerAnimated:YES];
}

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error{
    UIAlertView *alert;
	switch (result) {
		case MFMailComposeResultCancelled:
			break;
		case MFMailComposeResultFailed:
            alert = [[UIAlertView alloc] initWithTitle:@"MyApp" 
                                               message:@"Unknown Error"
                                              delegate:self 
                                     cancelButtonTitle:@"OK" 
                                     otherButtonTitles: nil];
			[alert show];
			[alert release];
			break;
		case MFMailComposeResultSent:
            
			break;
        case MFMailComposeResultSaved:
            break;
		default:
			break;
	}
	[self dismissModalViewControllerAnimated:YES];
}


@end
